﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Storage;

namespace MusicExplorer.Repository
{
    public static class RepositoryHelper
    {
        public static async Task<string> GetOnlineSourceAsync(string url)
        {
            var http = new System.Net.Http.HttpClient();
            var response = await http.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }

        public static async Task<string> GetLocalSourceAsync(string path)
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
            return await FileIO.ReadTextAsync(file);
        }

        private static List<Model.Repository> m_repositories;
        public static async Task<List<Model.Repository>> GetRepositoriesAsync()
        {
            if (m_repositories != null) return m_repositories;

            var dataUri = new Uri("ms-appx:///Data/Data.json");

            var file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
            string jsonText = await FileIO.ReadTextAsync(file);
            var jsonObject = JsonObject.Parse(jsonText);
            var jsonArray = jsonObject["Repositories"].GetArray();

            m_repositories = new List<Model.Repository>();
            foreach (var repoValue in jsonArray)
            {
                var repoObject = repoValue.GetObject();
                var repository = new Model.Repository();
                repository.Id = repoObject["Id"].GetString();
                repository.Name = repoObject["Name"].GetString();
                repository.WebSite = repoObject["WebSite"].GetString();
                repository.Image = repoObject["Image"].GetString();
                repository.ClassName = repoObject["ClassName"].GetString();
                m_repositories.Add(repository);
            }

            return m_repositories;
        }
    }
}
